import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:paly_android/api/api.dart';
import 'package:paly_android/base/base_widget.dart';
import 'package:paly_android/bloc/login_bloc.dart';
import 'package:paly_android/net/dio_client.dart';
import 'package:paly_android/route/routes.dart';
import 'package:paly_android/util/toast_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends BaseWidget {
  LoginPage({Key? key}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends BaseWidgetState<LoginPage> {
  TextEditingController _userNameController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  late LoginBloc _loginBloc;
  late LoginPwdBloc _loginPwdBloc;

  @override
  void initState() {
    _loginBloc = LoginBloc();
    _loginPwdBloc = LoginPwdBloc();
    _userNameController.addListener(_isShowDelete);
  }

  // bool _showDelete = false;

  void _isShowDelete() {
    // LogUtil.e("_isShowDelete 1111 $_showDelete");

    // _showDelete = _userNameController.text.isNotEmpty;
    _loginBloc.showDelUserName(_userNameController.text.isNotEmpty);
    // setState(() {
    //   LogUtil.e("_isShowDelete 22222 $_showDelete");
    // });
  }

  @override
  void dispose() {
    _userNameController.removeListener(_isShowDelete);
    super.dispose();
  }

  @override
  Widget baseBuild(BuildContext context) {
    return Form(
        autovalidateMode: AutovalidateMode.always, //开启自动校验
        child: Padding(
          padding: EdgeInsets.fromLTRB(15, 60, 15, 15),
          child: MultiBlocProvider(
              providers: [
                BlocProvider<LoginBloc>(create: (context) => _loginBloc),
                BlocProvider<LoginPwdBloc>(create: (context) => _loginPwdBloc),
              ],
              child: Column(
                children: [
                  Container(
                    width: double.infinity,
                    child: Text(
                      "密码登录",
                      style:
                      TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                    ),
                  ),
                  SizedBox(height: 20),
                  Stack(
                    children: <Widget>[
                      TextFormField(
                        maxLength: 11,
                        controller: _userNameController,
                        decoration: InputDecoration(
                            hintText: "请输入手机号", counterText: ""),
                        keyboardType: TextInputType.phone,
                        validator: (value) {
                          if (value!.isNotEmpty && value.length != 11) {
                            return "请输入正确的手机号";
                          }
                        },
                      ),
                      Positioned(
                        right: 0,
                        top: 20,
                        child: InkWell(onTap: () {
                          _userNameController.text = "";
                        }, child: BlocBuilder<LoginBloc, bool>(
                          builder: (context, state) {
                            return Visibility(
                              visible: state,
                              child: Image.asset(
                                "assets/images/login/icon_delete.png",
                                height: 15,
                              ),
                            );
                          },
                        )),
                      ),
                    ],
                  ),
                  SizedBox(height: 15),
                  BlocBuilder<LoginPwdBloc, bool>(
                    builder: (context, state) {
                      String path = state
                          ? "assets/images/login/icon_display.png"
                          : "assets/images/login/icon_hide.png";
                      return Stack(
                        alignment: AlignmentDirectional.center,
                        children: [
                          TextFormField(
                            controller: _pwdController,
                            obscureText: !state,
                            // decoration: InputDecoration(
                            //   border: OutlineInputBorder(
                            //     borderRadius: BorderRadius.circular(25.0),
                            //     borderSide: BorderSide(),
                            //   ),
                            //   hintText: "请输入密码",
                            // ),
                            validator: (value) {
                              value = value?.trim();
                              if (value!.isNotEmpty && value.length < 6) {
                                return "密码最少为6位";
                              }
                            },
                          ),
                          Positioned(
                            right: 10,
                            child: GestureDetector(
                              onTap: () {
                                _loginPwdBloc.showPwd(!state);
                              },
                              child: Image.asset(
                                path,
                                height: 15,
                              ),
                            ),
                          )
                        ],
                      );
                    },
                  ),
                  SizedBox(height: 50),
                  Container(
                    width: double.infinity,
                    child: ElevatedButton(
                      style: ButtonStyle(
                        // padding: MaterialStateProperty.all(EdgeInsets.all(30))
                          shape: MaterialStateProperty.all(
                              RoundedRectangleBorder(
                                  borderRadius:
                                  BorderRadius.all(Radius.circular(20))))),
                      child: Text("登录"),
                      onPressed: () {
                        String user = _userNameController.text;
                        String pwd = _pwdController.text;
                        if (user.isEmpty || pwd.isEmpty) {
                          showShortToast("账号或密码不能为空");
                          return;
                        }
                        LogUtil.e("user: $user   pwd:$pwd");

                        DioClient.instance.post<Map>(Api.LOGIN, parameters: {
                          "username": user,
                          "password": pwd
                        }).then((value) async {
                          final SharedPreferences prefs = await _prefs;
                          prefs
                              .setString("userId", value["id"].toString())
                              .then((value) =>
                          {
                            if (value)
                              Navigator.pushReplacementNamed(
                                  context, MyRouter.MAIN)
                          });
                        });
                      },
                    ),
                  ),
                  SizedBox(height: 10),
                  InkWell(
                    // style: ButtonStyle(
                    //   padding: MaterialStateProperty.all(EdgeInsets.all(30))
                    // ),
                    child: Text(
                      "没有账号?去注册",
                      style: TextStyle(color: Colors.blue),
                    ),
                    onTap: () {
                      Navigator.of(context).pushNamed("/register");
                    },
                  ),
                ],
              )),
        ));
  }

  @override
  String getAppBarTitle() => "登录";
}
